package com.leo.train.business.service.Impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.leo.train.business.dto.StationDto;
import com.leo.train.business.dto.StationQueryDto;
import com.leo.train.business.entity.Station;
import com.leo.train.business.mapper.StationMapper;
import com.leo.train.business.service.StationService;
import com.leo.train.common.exception.BusinessException;
import com.leo.train.common.exception.BusinessExceptionEnum;
import com.leo.train.common.resp.PageResult;
import com.leo.train.common.util.SnowUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class StationServiceImpl implements StationService {
    @Autowired
    private StationMapper stationMapper;
    /**
     * 保存
     * @param dto
     */
    @Override
    public void save(StationDto dto) {
        // 根据id判断是新增还是修改
        Long id = dto.getId();
        if(id == null) {
            // 查询输入站名是否存在
            Station station = selectByName(dto.getName());
            if(station != null) {
                throw new BusinessException(BusinessExceptionEnum.BUSINESS_STATION_NAME_UNIQUE_ERROR);
            }
            // 新增
            dto.setId(SnowUtil.getSnowflakeNextId());
            dto.setCreateTime(new Date());
            dto.setUpdateTime(new Date());
            stationMapper.insert(dto);
        } else {
            // 修改
            dto.setUpdateTime(new Date());
            stationMapper.update(dto);
        }

    }

    /**
     * 列表
     * @param queryDto
     * @return
     */
    @Override
    public PageResult list(StationQueryDto queryDto) {
        PageHelper.startPage(queryDto.getPage(), queryDto.getPageSize());
        Page<Station> page = stationMapper.selectList(queryDto);
        long total = page.getTotal();
        List<Station> list = page.getResult();
        return new PageResult(total, list);
    }

    @Override
    public StationDto detail(Long id) {
        return stationMapper.selectById(id);

    }

    @Override
    public void delete(Long id) {
        stationMapper.deleteById(id);
    }

    @Override
    public List<Station> listAll() {
        return stationMapper.selectAll();
    }

    /**
     * 定义一个唯一键方法
     */
    public Station selectByName(String name) {
        Station station = stationMapper.selectByName(name);
        if (station != null) {
            return station;
        }
        return null;
    }
}
